package com.dongnao.network.nio_hashcat;

import java.io.*;
import java.util.Map;

/**
 * @author sjy
 * @date 2024年05月12日 18:17
 */
public class HttpUtil {
    /**
     * 解析http请求的数据
     */
    public static HttpRequest resolve(byte[] data) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)));
        HttpRequest httpRequest = null;
        try {
            //解析请求的第一行，通过空格分割数据
            String[] s = reader.readLine().split(" ");
            httpRequest = new HttpRequest();

            //获取请求的url，请求的方法，http版本号
            String url = s[1];
            int index = url.indexOf("?");
            httpRequest.setUrl(index == -1 ? url : url.substring(0, index));
            httpRequest.setMethod(s[0]);
            httpRequest.setVersion(s[2]);

            //如果url中带了参数，解析参数
            if (index >= 0) {
                String[] params = url.substring(index + 1).split("&");
                for (String param : params) {
                    int eqi = param.indexOf("=");
                    httpRequest.getParams().put(param.substring(0, eqi), param.substring(eqi + 1));
                }
            }
            //解析请求的头信息
            String str;
            Map<String, String> headers = httpRequest.getHeaders();
            while ((str = reader.readLine()) != null) {
                if (str.length() == 0) {
                    break;
                }
                int idx = str.indexOf(":");
                headers.put(str.substring(0, idx), str.substring(idx + 1));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpRequest;
    }

    /**
     * 创建响应头信息
     *
     * @param code
     * @param contentLength
     * @return
     */
    public static String createResponseHeader(int code, long contentLength) {
        String strCode;
        if (code == 200) {
            strCode = "200 OK";
        } else {
            strCode = String.valueOf(code);
        }
        String str = "HTTP/1.1 " + strCode + "\r\n"
                + "Content-Type: text/html; charset=UTF-8\r\n"
                + "Content-Length: " + contentLength + "\r\n\r\n";
        return str;
    }
}
